package com.lanou.sfu.songforu.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.adapter.SearchAdapter;
import com.lanou.sfu.songforu.adapter.SearchHotAdapter;
import com.lanou.sfu.songforu.base.BaseFragment;
import com.lanou.sfu.songforu.constant.Url;
import com.lanou.sfu.songforu.datas.SearchHotDatas;
import com.lanou.sfu.songforu.datas.SearchSongEntity;
import com.lanou.sfu.songforu.datas.SongSearch;
import com.lanou.sfu.songforu.singleton.VolleySingleton;
import com.lanou.sfu.songforu.utils.net.FormatCodeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by quyan on 15/10/27.
 */
public class SearchFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private EditText searchETv; //搜索输入框
    private ArrayList<SearchSongEntity> data; //实体类
    private ListView songSearchLV; //列表布局
    Handler myhandler = new Handler();//开启新线程
    private SearchAdapter adapter;
    private VolleySingleton volleySingleton;
    private ImageView songSearchBackIV,searchIBtn;
    private GridView hotSecrch;
    private SearchHotDatas hotDatas;
    private List<SearchHotDatas.DataEntity> dataEntities;
    private SearchHotAdapter hotAdapter;
    private LinearLayout hotRecom;
    private ProgressDialog dialog;
    private SearchResultFragment fragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, null);
        songSearchLV = (ListView) view.findViewById(R.id.songSearchLV);
        songSearchLV.setOnItemClickListener(this);
        searchETv = (EditText) view.findViewById(R.id.searchETv);
        songSearchBackIV = (ImageView) view.findViewById(R.id.songSearchBackIV);
        hotSecrch = (GridView) view.findViewById(R.id.hotSearch);
        hotSecrch.setOnItemClickListener(this);
        hotRecom = (LinearLayout) view.findViewById(R.id.hotRecom);
        searchIBtn = (ImageView) view.findViewById(R.id.searchIBtn);
        searchIBtn.setOnClickListener(this);
        songSearchBackIV.setOnClickListener(this);
        TextChanged();
        //数据出现时候点击删除的方法
        //DeleteTextOnClick();

        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        volleySingleton = VolleySingleton.getInstance(getActivity());
        addData();
    }

    //文本改变方法
    public void TextChanged() {
        searchETv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    getFragmentManager().beginTransaction().remove(fragment).commit();
                    //显示gridview内容
                    hotRecom.setVisibility(View.VISIBLE);
                    //隐藏ListView
                    songSearchLV.setVisibility(View.GONE);
                } else {
                    //不显示gridview内容
                    hotRecom.setVisibility(View.GONE);
                    //显示ListView
                    songSearchLV.setVisibility(View.VISIBLE);
                }
                //把数据加入到请求队列
                myhandler.post(runnable);
            }
        });
    }
    //利用线程实现界面更新
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //获取数据
            final String datas = searchETv.getText().toString();
            //转为utf_8
            String songurl = FormatCodeUtil.codingFormat(datas);
            //网址拼接
            String url = Url.URL_SEARCH + songurl;
            //网络请求
            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    //获取数据
                    data = songSearch.getSong();
                    adapter = new SearchAdapter(getActivity(), data);
                    songSearchLV.setAdapter(adapter);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(request);

        }
    };
    //热门搜索解析
    public void addData(){
        String url = Url.URL_SEARCH_HOT;
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Gson gson = new Gson();
            hotDatas = gson.fromJson(response, SearchHotDatas.class);
            dataEntities = hotDatas.getData();
            hotAdapter = new SearchHotAdapter(getActivity(),dataEntities);
            hotSecrch.setAdapter(hotAdapter);

            if (dialog.isShowing()){
                dialog.dismiss();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage(getActivity().getString(R.string.loading));
        dialog.show();
        volleySingleton.addQueue(request);//添加队列

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.songSearchBackIV:
                getFragmentManager().popBackStack();//返回
                break;
            case R.id.searchIBtn:
                //获取数据
                final String datas = searchETv.getText().toString();
                if (datas.trim().length() == 0){
                    Toast.makeText(getActivity(), R.string.PLEASE_EDIT,Toast.LENGTH_SHORT).show();
                }
                //转为utf_8
                String songurl = FormatCodeUtil.codingFormat(datas);
                //网址拼接
                //String url = Url.URL_SEARCH + songurl;
                fragment = new SearchResultFragment();
                Bundle bundle = new Bundle();//传值
                bundle.putString("url",songurl);
                fragment.setArguments(bundle);
                //替换Fragment
                getFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.replace,fragment)
                        .commit();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()){
            //点击gridview传数据
            case R.id.hotSearch:
                TextView textView = (TextView) view.findViewById(R.id.hotSecrchText);
                String text = textView.getText().toString();//获取字段
                String str = FormatCodeUtil.codingFormat(text);//转为utf-8
                //Bundle传值
                Bundle bundle = new Bundle();
                bundle.putString("url",str);
                fragment = new SearchResultFragment();
                fragment.setArguments(bundle);
                getFragmentManager().beginTransaction().addToBackStack(null)
                        .replace(R.id.replace,fragment).commit();
                break;
            case R.id.songSearchLV://点击ListView传数据
                TextView textView1 = (TextView) view.findViewById(R.id.searchSongName);
                String text1 = textView1.getText().toString();//获取字段
                String str1 = FormatCodeUtil.codingFormat(text1);//转为utf-8
                //Bundle传值
                Bundle bundle1 = new Bundle();
                bundle1.putString("url",str1);
                fragment = new SearchResultFragment();
                fragment.setArguments(bundle1);
                getFragmentManager().beginTransaction().addToBackStack(null)
                        .replace(R.id.replace,fragment).commit();
                break;
        }
    }
}